// pages/post/comment/comment.js
const app = getApp();
const request = require('../../../utils/request.js');
const config = require('../../../utils/config');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    colorTheme: app.globalData.colorTheme,
    toUid: -1,
    commentId: -1,
    keyBoardHeight: 0,
    isFocus: false,
    clearValue: '',
    inputPlaceholder: '',
    commentInfo: {}
  },

  /**
   * 获取帖子评论列表
   */
  getCommentList(){
    let that = this;
    let url = config.SERVER_URL + 'comment/listCommentOfPost/' + this.data.commentInfo.postId;
    let token = wx.getStorageSync('token');
    let params = {
      pageNum: 1,
      pageSize: 100
    }
    request.requestGetApi(url, token, params, 'application/json').then(res=>{
      if(res.status === config.STATUS_OK){
        res.data.rows.find((item, index)=>{
          if(item.id === that.data.commentId){
            that.setData({
              commentInfo: item
            });
          }
        });
      }
    }).catch(err=>{
      app.failFun(err);
    }).finally((res) => {
      app.completeFun(res);
    });;
  },

  /**
   * 提交评论
   */
  submitComment(e){
    if(!app.checkedUserLoading()){
      return;
    }
    let that = this;
    let params = e.detail.value;
    if(typeof params !== 'object'){
      let content = params;
      params = { content };
    }
    params.postId = this.data.commentInfo.postId;
    params.toUid = this.data.toUid;
    params.parentCommentId = this.data.commentInfo.id;
    let token = wx.getStorageSync('token');
    let url = config.SERVER_URL + 'comment/replyToComments';
    wx.showLoading({
      title: '评论中...'
    });
    request.requestPostApi(url, token, params, 'application/json').then(res=>{
      if(res.status === config.STATUS_OK){
        that.setData({
          clearValue: ''
        });
        that.getCommentList();
        wx.showToast({
          title: res.message,
          icon: 'success',
          duration: 1500
        });
      }
    }).catch(err=>{
      app.failFun(err);
    })
  },

  /**
   * 点赞或取消点赞评论
   */
  likeorUnLikeComment(e){
    if(!app.checkedUserLoading()){
      return;
    }
    let commentInfo = this.data.commentInfo;
    let childCommentsInfo, index;
    index = e.currentTarget.dataset.index;
    childCommentsInfo = this.data.commentInfo.childComments[index];
    let that = this;
    let token = wx.getStorageSync('token');
    let url = config.SERVER_URL;
    if(childCommentsInfo.like){
      url += 'comment/cancelLikesComment/' + childCommentsInfo.id;
      childCommentsInfo.likes--;
    }else{
      url += 'comment/likesComment/' + childCommentsInfo.id;
      childCommentsInfo.likes++;
    }
    childCommentsInfo.like = !childCommentsInfo.like;
    commentInfo.childComments[index] = childCommentsInfo;
    request.requestPostApi(url, token, {}, 'application/json').then(res=>{
      if(res.status === config.STATUS_OK){
        that.setData({
          commentInfo
        });
      }
    }).catch(err=>{
      app.failFun(err);
    });
  },

  /**
   * 删除自己的评论
   */
  deleteComment(e){
    if(!app.checkedUserLoading()){
      return;
    }
    let that = this;
    let commentInfo = this.data.commentInfo;
    let index = e.currentTarget.dataset.index;
    let childCommentsInfo = commentInfo.childComments[index];
    let userId = wx.getStorageSync('userInfo').uid;
    if(childCommentsInfo.fromUid !== userId){
      return;
    }
    wx.showModal({
      title: '提示',
      content: '确定要删除这条回复吗？',
      confirmText: '确认删除',
      confirmColor: '#0081ff',
      success: (result) => {
        if(result.confirm){
          let token = wx.getStorageSync('token');
          let url = config.SERVER_URL + 'comment/delComment/' + childCommentsInfo.id;
          commentInfo.childComments.splice(index, 1);
          request.requestPostApi(url, token, {}, 'application/json').then(res=>{
            if(res.status === config.STATUS_OK){
              that.setData({
                commentInfo
              });
              wx.showToast({
                title: res.message,
                icon: 'success',
                duration: 1500,
              });
            }
          }).catch(err=>{
            app.failFun(err);
          });
        }
      }
    });
  },

  /**
   * 评论文本框获得焦点
   */
  focusComment(){
    this.setData({
      isFocus: true
    });
  },

  /**
   * 评论文本框失去焦点
   */
  blurComment(){
    this.setData({
      isFocus: false,
      inputPlaceholder: this.data.commentInfo.nickname,
      toUid: this.data.commentInfo.fromUid
    });
  },

  /**
   * 获取键盘高度变化
   */
  getKeyboardHeight(e){
    this.setData({
      keyBoardHeight: e.detail.height
    });
  },

  /**
   * 获取回复用户名称
   */
  replyUser(e){
    if(!app.checkedUserLoading()){
      return;
    }
    let index = e.currentTarget.dataset.index;
    let commentInfo = this.data.commentInfo;
    let comment = commentInfo.childComments[index];
    let userId = wx.getStorageSync('userInfo').uid;
    if(comment.fromUid === userId){
      return;
    }
    this.setData({
      inputPlaceholder: comment.fromNickname,
      toUid: comment.fromUid,
      isFocus: true
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      commentInfo: JSON.parse(options.commentInfo),
    });
    setTimeout(()=>{
      this.setData({
        inputPlaceholder: this.data.commentInfo.nickname,
        toUid: this.data.commentInfo.fromUid,
        commentId: this.data.commentInfo.id
      });
    }, 20);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})